#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/24 21:56
# @Author  : leon yan
# @Site    : 
# @File    : SystemSet.py
# @Software: PyCharm

from PyQt5.QtCore import pyqtSlot, QStringListModel, Qt
from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox, QAbstractItemView

import Globalist as gl
from lib.fileprocess import cfgProcess
from resource.SystemSet_ui import Ui_QWFormTable


class QSystemSet(QMainWindow, Ui_QWFormTable):

    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        # gl.init()   # for
        self.model = QStringListModel(self)
        self.listPowerIp.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.model.setStringList([])
        self.listPowerIp.setModel(self.model)
        self.rdCfg = cfgProcess.get_cfg_JsonData(r".\api\.powerCfg")
        self.rdSystemSet()

    def __del__(self):
        print("SystemSet is deleted")

    def rdSystemSet(self):
        # Pc
        aa = gl.get_value("socketPort")
        self.spinSocketPort.setValue(int(aa))
        # QRCode
        aa = gl.get_value("qr_version")
        self.qrVersion.setValue(int(aa))
        aa = gl.get_value("qr_size")
        self.qrSize.setValue(int(aa))
        aa = gl.get_value("qr_error")
        self.qrError.setCurrentIndex(int(aa))
        aa = self.rdCfg["save_power_meter_ip"]
        if aa:
            bb = []
            for k, v in aa.items():
                bb.append(v[0] + "_" + v[3])
            self.model.setStringList(bb)
            self.listPowerIp.setModel(self.model)

    @pyqtSlot()
    def on_btnAdd_clicked(self):
        if not self.linePowerId.text():
            QMessageBox.warning(self, "警告", "无数据!")
            return
        elif (not self.radioChint.isChecked()) and (not self.radioPanasonic.isChecked()):
            QMessageBox.warning(self, "警告", "必须选择电表品牌!")
            return
        else:
            aa = ""
            if self.radioChint.isChecked():
                aa = self.linePowerId.text() + "_" + self.radioChint.text()
            elif self.radioPanasonic.isChecked():
                aa = self.linePowerId.text() + "_" + self.radioPanasonic.text()
            if aa:
                lastRow = self.model.rowCount()
                self.model.insertRow(lastRow)
                index = self.model.index(lastRow, 0)
                self.model.setData(index, aa, Qt.DisplayRole)
                self.listPowerIp.setCurrentIndex(index)
                self.linePowerId.setText("")

    @pyqtSlot()
    def on_btnDel_clicked(self):
        index = self.listPowerIp.currentIndex()
        if index.row() >= 0:
            self.model.removeRow(index.row())
        else:
            QMessageBox.warning(self, "警告", "未选择!")

    @pyqtSlot()
    def on_btnCancel_clicked(self):
        self.rdSystemSet()

    @pyqtSlot()
    def on_btnSave_clicked(self):
        gl.global_config["Pc"]['socketPort'] = self.spinSocketPort.value()

        gl.global_config['QRCode']["version"] = self.qrVersion.value()
        gl.global_config['QRCode']["size"] = self.qrSize.value()
        gl.global_config['QRCode']["error"] = self.qrError.currentIndex()

        strList = self.model.stringList()
        aa = {}
        for i in range(len(strList)):
            bb = strList[i].split("_")
            bb2 = []
            if bb[1] == "chint":
                bb2 = [bb[0], 16415, 0.0, bb[1]]
            elif bb[1] == "panasonic":
                bb2 = [bb[0], 106, 0.0, bb[1]]
            aa[str(i)] = bb2
        self.rdCfg["save_power_meter_ip"] = aa

        gl.global_config.write()
        cfgProcess.set_cfg_json(r".\api\.powerCfg", self.rdCfg)

        aa = gl.global_config['Pc']["socketPort"]
        gl.set_value("socketPort", int(aa))

        aa = gl.global_config['QRCode']["version"]
        gl.set_value("qr_version", int(aa))
        aa = gl.global_config['QRCode']["size"]
        gl.set_value("qr_size", int(aa))
        aa = gl.global_config['QRCode']["error"]
        gl.set_value("qr_error", int(aa))

        gl.global_var["watt_hour_meter_ip"] = cfgProcess.get_cfg_JsonData(r".\api\.powerCfg")["save_power_meter_ip"]

        QMessageBox.information(self, "Tips", "保存成功!")

    def intChk(self, inputStr):
        try:
            aa = int(inputStr)
            if 0 < aa <= 255:
                return aa
            else:
                QMessageBox.warning(self, "Warning", "Data error!")
                return None
        except Exception as e:
            QMessageBox.warning(self, "Warning", "Data error!")
            print(e)
            return None


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    objWindow = QSystemSet()

    objWindow.show()
    sys.exit(app.exec_())
